package com.agent.auth.service;

import org.springframework.stereotype.Service;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;

/**
 * 管理员登录异常限制
 */
@Service
public class LoginAttemptService {
    // 存储登录尝试记录：Key=用户名, Value=包含尝试次数和锁定时间戳的对象
    private final ConcurrentMap<String, AttemptRecord> attemptsCache = new ConcurrentHashMap<>();
    private static final int MAX_ATTEMPTS = 5;
    private static final long LOCK_TIME_MINUTES = 15;
    private static final long LOCK_TIME_MILLIS = TimeUnit.MINUTES.toMillis(LOCK_TIME_MINUTES);

    public void loginFailed(String username) {
        attemptsCache.compute(username, (key, record) -> {
            // 首次失败或已有记录但未锁定
            if (record == null || record.isExpired()) {
                return new AttemptRecord(1, System.currentTimeMillis());
            }
            // 已有有效记录：增加尝试次数并更新时间戳
            return new AttemptRecord(record.attempts + 1, System.currentTimeMillis());
        });
    }

    public void loginSucceeded(String username) {
        attemptsCache.remove(username);
    }

    public boolean isBlocked(String username) {
        AttemptRecord record = attemptsCache.get(username);
        // 无记录或记录已过期 → 未锁定
        if (record == null || record.isExpired()) {
            return false;
        }
        // 检查尝试次数是否超过阈值
        return record.attempts >= MAX_ATTEMPTS;
    }

    // 内部类：存储登录尝试记录
    private static class AttemptRecord {
        private final int attempts;      // 尝试次数
        private final long lockTimestamp; // 最后一次失败的时间戳（毫秒）

        AttemptRecord(int attempts, long lockTimestamp) {
            this.attempts = attempts;
            this.lockTimestamp = lockTimestamp;
        }

        // 检查锁定是否过期
        boolean isExpired() {
            return System.currentTimeMillis() - lockTimestamp > LOCK_TIME_MILLIS;
        }
    }
}